# -*- coding: utf-8 -*-
from PIL import Image, ImageEnhance
#from core.config import RESIZE_QUALITY
RESIZE_QUALITY = 90

import math


def new_resize(img, size, path = None):
    im = Image.open(img)
    if im.mode not in ('L', 'RGB'):
       im = im.convert('RGB')
    
    
    width_orig = float(im.size[0])
    height_orig = float(im.size[1])
    
    width = float(size[0])
    height = float(size[1])
   
    
    if width_orig > width or height_orig > height:
        if width_orig > height_orig:
            
            new_height =  math.ceil( float(height_orig / width_orig) * width )
           
            new_width = width
           
        
        else:
            new_width = math.ceil( float( width_orig * height / height_orig ) )
            new_height = height
           
        im = im.resize( (new_width,new_height ), Image.ANTIALIAS)
            
        if path:
            im.save(path, quality=RESIZE_QUALITY)
        else:
            im.save(img, quality=RESIZE_QUALITY)
        
        
        
    else:
        if path:
            im.save(path, quality=RESIZE_QUALITY)
        else:
            im.save(img, quality=RESIZE_QUALITY)
            
        
    
    
    
    
def resize(imagename,width,height,path='', strict = True):
   #print imagename
   
   im = Image.open(imagename)
   
   if im.mode not in ('L', 'RGB'):
       im = im.convert('RGB')

   
   width_orig = im.size[0]
   height_orig = im.size[1]
   if width_orig > width or height_orig > height:
       if height_orig > width_orig:
          width = width * height_orig / width_orig
       else:
          height = width_orig * height / height_orig
       new_size = (width,height)
       
         
       if strict:
           imagesize = im.size
        
           output_size = ( width, height )
            
           m_width = float(output_size[0])
           m_height = float(output_size[1])
          
           w_k = imagesize[0]/m_width
           h_k = imagesize[1]/m_height
           if output_size < imagesize:
               if w_k > h_k:
                   new_size = (m_width, imagesize[1]/w_k)
               else:
                   new_size = (imagesize[0]/h_k, m_height)
           else:
               new_size = imagesize
            #print int( new_size[0] ), int( new_size[1] )
       
       im = im.resize(new_size, Image.ANTIALIAS)
       
       if path: im.save(path, quality=RESIZE_QUALITY)
       
       else: 
           #im = watermark(im)       
           im.save(imagename, quality=RESIZE_QUALITY)
   else:
       if path:
           im.save(path, quality=RESIZE_QUALITY)
       else:
           im.save(imagename, quality=RESIZE_QUALITY)
            


def crop_resize(src,dest,sizing,position=''):
    needed_width = sizing[0]
    needed_height = sizing[1]
    im = Image.open(src)
    size = im.size
    cut_width = round(math.ceil(size[0] / needed_width))
    cut_height = round(math.ceil(size[1] / needed_height))
    cr = False
    if position=='centerTop':
        center_x = round(size[0] / 2)
        center_y = round(size[1] / 2)
        box=(center_x-round(needed_width/2)*cut_width, 0 ,center_x+round(needed_width/2)*cut_width,round(needed_height)*cut_width)
    if position=='center':
        center_x = round(size[0] / 2)
        center_y = round(size[1] / 2)
        
        x1 = center_x - (needed_width / 2 )* cut_width 
        x2 =center_x + (needed_width /2 ) * cut_width
        y1 = center_y - (needed_height / 2) * cut_width
        y2= center_y + (needed_height / 2) * cut_width
        
        box=(x1,y1,x2,y2)
   
    if position=='cropCoop':
        cr = True
        box=(0,0,size[0],size[1]-50)
    im = im.crop(box)
    width_orig = im.size[0]
    height_orig = im.size[1]

    if not cr:
        im = im.resize((needed_width, needed_height), Image.ANTIALIAS)
    im.save(dest)
    

def watermark(im, position=(10, 10), opacity=0.8):
    """Добавляем к кортинке прозрачный водяной знак."""
    mark = Image.open('D:/!server/taketrip/usr/m.png')
    if opacity < 1:
        """Вычисляем прозрачность."""
        assert opacity >= 0 and opacity <= 1
        if im.mode != 'RGBA':
            mark = mark.convert('RGBA')
        else:
            mark = mark.copy()
        alpha = mark.split()[3]
        alpha = ImageEnhance.Brightness(alpha).enhance(opacity)
        mark.putalpha(alpha)
    if im.mode != 'RGBA':
        im = im.convert('RGBA')
    # create a transparent layer the size of the image and draw the
    # watermark in that layer.
    layer = Image.new('RGBA', im.size, (0,0,0,0))
    if position == 'tile':
        for y in range(0, im.size[1], mark.size[1]):
            for x in range(0, im.size[0], mark.size[0]):
                layer.paste(mark, (x, y))
    elif position == 'scale':
        # scale, but preserve the aspect ratio
        ratio = min(
            float(im.size[0]) / mark.size[0], float(im.size[1]) / mark.size[1])
        w = int(mark.size[0] * ratio)
        h = int(mark.size[1] * ratio)
        mark = mark.resize((w, h))
        layer.paste(mark, ((im.size[0] - w) / 2, (im.size[1] - h) / 2))
    else:
        layer.paste(mark, position)
    return Image.composite(layer, im, layer)
